package com.iswitch.iswitch;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothSocket;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.iswitch.ui.SwitchButton;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class LanYaMainActivity extends Activity implements OnClickListener {
    private String Tag = "LanYaMainActivity";

    private Button kaiDianJi, guanDianJi, safeOn;
    private Button start, stop, reset, resetAll,jiTing;
    private Button heightAdd, heightSub, buChangAdd, buChangSub, speedAdd, speedSub, yuShengSong, yuShengJin;
    private Button zhiNengXueXi, ziDongTiChui, fangShangTianLun, zhiNengPaiSheng, jinChiJiaSu;

    private Button duanKai,qingkong;
    //+++++++++++++++++++++
    private ImageView shache_jia;
    private ImageView shache_jian, lihe_jia, lihe_jian;
    //+++++++++++++++++++++
    private Switch aSwitch;
    // private Switch duanshuangda;
    public final static int SENDPOS = 100;
    public final static String FNAME = "FNAME";
    private final static int REQUEST_CONNECT_DEVICE = 1; // 宏定义查询设备句柄
    private final static int REQUEST_CONNECT_DEVIC_OLD = 2; // 宏定义查询设备句柄
    private final static int REQUEST_DATA = 2;
    private final static String MY_UUID3 = "0000FF12-0000-1000-8000-00805F9B34FB"; //服务
    private final static String MY_UUID = "0000FF01-0000-1000-8000-00805F9B34FB"; //从手机端往电脑端发送数据则选择这个特征
    final UUID UUID_SERVICE = UUID.fromString(MY_UUID3);
    //
    //  设备特征值UUID, 需固件配合同时修改
    //
    final UUID UUID_WRITE = UUID.fromString(MY_UUID);  // 用于发送数据到设备
    protected static final int REQUEST_ENABLE = 0;
    private final static String START_CMD_PUTY = "OPEN";
    private final static String STOP_CMD_PUTY = "STOP";

    private InputStream is; // 输入流，用来接收蓝牙数据

    private TextView jieshouqu; // 接收数据显示句柄
    private ScrollView jieshouqu_scroll_view; // 翻页句柄
    private String smsg = ""; // 显示用数据缓存
    int MAX = 4096;
    byte[] all = new byte[MAX];
    int allPos = 0;


    BluetoothDevice _device = null; // 蓝牙设备
    BluetoothSocket _socket = null; // 蓝牙通信socket
    boolean _discoveryFinished = false;
    boolean bRun = true;
    boolean bThread = false;
    boolean hex = false;

    private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter(); // 获取本地蓝牙适配器，即蓝牙设备
    private BluetoothLeScanner scanner;
    private ScanCallback mScanCallback;
    private BluetoothGatt mBluetoothGatt;
    private String selectedAddress ;
    private Button btnsearch;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    //+++++++++++++++++++++
    private TextView height_value;
    private TextView rope_value;
    private TextView speed_value;//速度
    private TextView shache_qiya;//刹车气压
    private TextView lihe_qiya;//离合气压
    private TextView tv_A;//大电流
    private TextView tv_V;//总气压
    private SwitchButton suo;
    private ImageView icon_suo;


    private boolean dianjikai;

    //+++++++++++++++++++++++
    public void initView() {

        duanKai = (Button) findViewById(R.id.duan_kai);
        duanKai.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                disconnect();
//                removePairDevice();
            }
        });
        qingkong = (Button) findViewById(R.id.qingkong);
        qingkong.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                removePairDevice();
            }
        });

        start = (Button) findViewById(R.id.qidong);
        start.setOnClickListener(this);
        stop = (Button) findViewById(R.id.stop);
        stop.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.qidong:
                //启动
                sendString(START_CMD_PUTY);
                break;
            case R.id.stop:
                //停止
                sendString(STOP_CMD_PUTY);
                break;
            default:
                break;
        }
    }

    public void sendString(String cmd) {
        if (mBluetoothGatt != null) {
            BluetoothGattService gattService = mBluetoothGatt.getService(UUID_SERVICE);
            BluetoothGattCharacteristic characteristic = gattService.getCharacteristic(UUID_WRITE);
            byte[] bytes = new byte[2];
            bytes[0] = 04;
            bytes[1] = 01;
            characteristic.setValue(cmd);
            characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
            mBluetoothGatt.writeCharacteristic(characteristic);
        }

    }

    public void disconnect() {
        if (_socket != null) {
            //取消注册异常断开接收器
            this.unregisterReceiver(mReceiver);


            // 关闭连接socket
            try {
                _socket.close();
                _socket = null;

                //btnadd.setText(getResources().getString(R.string.add));
            } catch (IOException e) {
            }
        }
        if (mBluetoothGatt != null) {
            mBluetoothGatt.close();
        }
        SharedPreferences.Editor sharedata = getSharedPreferences("Lanya", 0).edit();
        sharedata.clear();
        sharedata.commit();

        mPairedDevicesArrayAdapter.clear();
        Toast.makeText(this, "线路已断开，请重新连接！", Toast.LENGTH_SHORT).show();
    }

    public void search() {
        if (_bluetooth.isEnabled() == false) { // 如果蓝牙服务不可用则提示
            //询问打开蓝牙
            Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enabler, REQUEST_ENABLE);
            return;
        }

        // 如未连接设备则打开DeviceListActivity进行设备搜索
//        if (_socket == null) {
            Intent serverIntent = new Intent(LanYaMainActivity.this,
                    DeviceListActivity.class); // 跳转程序设置
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); // 设置返回宏定义
//        }
        return;

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lanya_new);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            }
            if (this.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, 1);
            }
        }
        initView();

        btnsearch = (Button) findViewById(R.id.search);
        btnsearch.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                search();
            }
        });
        mScanCallback = new LeScanCallback();
        // 如果打开本地蓝牙设备不成功，提示信息，结束程序
        if (_bluetooth == null) {
            Toast.makeText(this, "本机没有找到蓝牙硬件或驱动！", Toast.LENGTH_LONG)
                    .show();
            finish();
            return;
        }
        if (_bluetooth.isEnabled() == false) { // 如果蓝牙服务不可用则提示
            Toast.makeText(LanYaMainActivity.this, " 打开蓝牙中...",
                    Toast.LENGTH_SHORT).show();

            new Thread() {
                public void run() {
                    if (_bluetooth.isEnabled() == false) {
                        _bluetooth.enable();
                    }
                }
            }.start();
        }
        if (_bluetooth.isEnabled() == false) {//这个五秒就表明上一步应该可以正式搞定了。
            Toast.makeText(LanYaMainActivity.this, "等待蓝牙打开，5秒后，尝试连接！", Toast.LENGTH_SHORT).show();
            new Handler().postDelayed(new Runnable() {   //延迟执行
                @Override
                public void run() {
                    if (_bluetooth.isEnabled() == false) {
                        Toast.makeText(LanYaMainActivity.this, "自动打开蓝牙失败，请手动打开蓝牙！", Toast.LENGTH_SHORT).show();
                        //询问打开蓝牙
                        Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enabler, REQUEST_ENABLE);
                    } else
                        search(); //自动进入连接

                }
            }, 5000);

        } else {
            search(); //自动进入连接
        }
    }


    public static byte[] hexStringToBytes(String hexString) {
        hexString = hexString.replaceAll(" ", ""); // 去空格
        if ((hexString == null) || (hexString.equals(""))) {
            return null;
        }
        hexString = hexString.toUpperCase(); // 字符串中的所有字母都被转化为大写字母
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; ++i) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[(pos + 1)]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    // 发送响应
    // 调用这个方法发送数据到单片机。
    public boolean sendString2(String str) {
        if (_socket == null) {
            Toast.makeText(this, "未连接蓝牙", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (str == null) {
            Toast.makeText(this, "发送内容为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        try {

            OutputStream os = _socket.getOutputStream(); // 蓝牙连接输出流
            if (hex) {

                byte[] bos_hex = hexStringToBytes(str); // 十六进制
                os.write(bos_hex);
            } else {
                byte[] bos = str.getBytes("GB2312");    //native的Socket发送字节流默认是GB2312的，所以在Java方面需要指定GB2312
                os.write(bos);
            }

        } catch (IOException e) {
        }
        return true;
    }


    // 关闭程序掉用处理部分
    public void onDestroy() {
        super.onDestroy();
        if (_socket != null) // 关闭连接socket
            try {
                _socket.close();
            } catch (IOException e) {
            }

        _bluetooth.disable(); //关闭蓝牙服务
        if (mBluetoothGatt != null) {
            mBluetoothGatt.close();
        }
        //  android.os.Process.killProcess(android.os.Process.myPid()); // 终止线程
    }
    private class LeScanCallback  extends ScanCallback {

        /**
         * 扫描结果的回调，每次扫描到一个设备，就调用一次。
         * @param callbackType
         * @param result
         */
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            //Log.d(Tag, "onScanResult");
            if(result != null){
                if (result.getDevice().getAddress() != null && selectedAddress.equals(result.getDevice().getAddress())) {
                    //扫描到我们想要的设备后，立即停止扫描
                    mBluetoothGatt = result.getDevice().connectGatt(LanYaMainActivity.this, false, mGattCallback);
                    scanner.stopScan(mScanCallback);
                }
            }
        }
    }
    private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

        /**
         * Callback indicating when GATT client has connected/disconnected to/from a remote GATT server
         *
         * @param gatt 返回连接建立的gatt对象
         * @param status 返回的是此次gatt操作的结果，成功了返回0
         * @param newState 每次client连接或断开连接状态变化，STATE_CONNECTED 0，STATE_CONNECTING 1,STATE_DISCONNECTED 2,STATE_DISCONNECTING 3
         */
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            Log.d(Tag, "onConnectionStateChange status:" + status + "  newState:" + newState);
            if (status == 0) {
                gatt.discoverServices();
            }
        }

        /**
         * Callback invoked when the list of remote services, characteristics and descriptors for the remote device have been updated, ie new services have been discovered.
         *
         * @param gatt 返回的是本次连接的gatt对象
         * @param status
         */
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            Log.d(Tag, "onServicesDiscovered status" + status);
            List<BluetoothGattService> mServiceList = gatt.getServices();
            if (mServiceList != null) {
//                System.out.println(mServiceList);
//                System.out.println("Services num:" + mServiceList.size());
            }

            for (BluetoothGattService service : mServiceList){
                List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
//                System.out.println("扫描到Service：" + service.getUuid());

                for (BluetoothGattCharacteristic characteristic : characteristics) {
//                    System.out.println("characteristic: " + characteristic.getUuid() );
                }
            }
        }

        /**
         * Callback triggered as a result of a remote characteristic notification.
         *
         * @param gatt
         * @param characteristic
         */
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            Log.d(Tag, "onCharacteristicChanged");
        }

        /**
         * Callback indicating the result of a characteristic write operation.
         *
         * @param gatt
         * @param characteristic
         * @param status
         */
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            Log.d(Tag, "onCharacteristicWrite");
        }

        /**
         *Callback reporting the result of a characteristic read operation.
         *
         * @param gatt
         * @param characteristic
         * @param status
         */
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            Log.d(Tag, "onCharacteristicRead");
        }

        /**
         * Callback indicating the result of a descriptor write operation.
         *
         * @param gatt
         * @param descriptor
         * @param status
         */
        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            Log.d(Tag, "onDescriptorWrite");
        }

    };

    // 接收活动结果，响应startActivityForResult()
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE: // 连接结果，由DeviceListActivity设置返回
                // 响应返回结果
                if (resultCode == Activity.RESULT_OK) { // 连接成功，由DeviceListActivity设置返回
                    // MAC地址，由DeviceListActivity设置返回
                    selectedAddress = data.getExtras().getString(
                            DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    scanner = _bluetooth.getBluetoothLeScanner();
                    scanner.startScan(mScanCallback);
                }
                break;
            case REQUEST_CONNECT_DEVIC_OLD: // 连接结果，由DeviceListActivity设置返回
                // 响应返回结果
                if (resultCode == Activity.RESULT_OK) { // 连接成功，由DeviceListActivity设置返回
                    // MAC地址，由DeviceListActivity设置返回
                    String address = data.getExtras().getString(
                            DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    // 得到蓝牙设备句柄
                    _device = _bluetooth.getRemoteDevice(address);
                    // 用服务号得到socket
                    try {
                        _socket = _device.createRfcommSocketToServiceRecord(UUID
                                .fromString(MY_UUID));
                    } catch (IOException e) {

                        Toast.makeText(this, "连接失败,无法得到Socket！" + e, Toast.LENGTH_SHORT).show();

                    }


                    // 连接socket
                    try {
                        _socket.connect();

                        Toast.makeText(this, "连接" + _device.getName() + "成功！",
                                Toast.LENGTH_SHORT).show();
                        SharedPreferences.Editor sharedata = getSharedPreferences("Lanya", 0).edit();
                        sharedata.putString(String.valueOf(0), _device.getName());
                        sharedata.putString(String.valueOf(1), _device.getAddress());
                        sharedata.commit();


                        //注册异常断开接收器  等连接成功后注册
                        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
                        this.registerReceiver(mReceiver, filter);

                    } catch (IOException e) {

                        try {
                            Toast.makeText(this, "连接失败！" + e, Toast.LENGTH_SHORT)
                                    .show();
                            _socket.close();
                            _socket = null;
                        } catch (IOException ee) {
                        }
                        return;
                    }

                }
                break;
            default:
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {

                disconnect();
            }
        }
    };

    //得到配对的设备列表，清除已配对的设备
    public void removePairDevice(){
        if(_bluetooth!=null){
            Set<BluetoothDevice> bondedDevices = _bluetooth.getBondedDevices();
            for(BluetoothDevice device : bondedDevices ){
                unpairDevice(device);
            }
        }

    }

    //反射来调用BluetoothDevice.removeBond取消设备的配对
    private void unpairDevice(BluetoothDevice device) {
        try {
            Method m = device.getClass()
                    .getMethod("removeBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
        } catch (Exception e) {
        }
    }

}

